import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/pages/mall_app/commodity_search/shop_search/state.dart';
import 'package:yp/services/api.dart';

import '../../../../helper.dart';
import '../../../../router.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class ShopSearchLogic extends GetxController {
  final ShopSearchState state = ShopSearchState();
  final MainLogic mainLogic = Get.put(MainLogic());

  @override
  void onInit() {
    super.onInit();
    state.searchTextEditingController.text = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
    getSearchShopList();
    getAdvertising();
  }

  /// 搜索店铺
  void getSearchShopList() {
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      'shop_name': state.searchTextEditingController.text.trim(),
    };
    Api.searchShopList(params).listen((event) {
      state.refreshController.loadComplete();
      state.refreshController.refreshCompleted();
      if (event != null && event["code"] == 0 && event['ec_shops'] != null) {
        print(event);
        state.shopInfoList = event['ec_shops'];
        update();
      }
      if (state.shopInfoList.length == 0) {
        getRecommendCommodityList();
        getAdvertising();
      }
    });
  }

  /// 下拉刷新
  void refreshData() {
    state.currentPage = 1;
    getSearchShopList();
    state.refreshController.refreshCompleted();
  }

  /// 上拉加载更多
  void loadMoreData() {
    state.currentPage++;
    getSearchShopList();
    state.refreshController.loadComplete();
  }

  /// 获取推荐商品列表
  void getRecommendCommodityList() {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "use_platform": 2,
        "is_recommend": 1,
        // "shop_id": SpUtil.getInt("storeShopNum"),
        "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        "page_no": 1,
        "page_size": 10,
        "access_token": SpUtil.getString('token')
      };
      Api.recommendGoods(params).listen((event) {
        print("获取推荐商品列表11:$event");
        if (event["code"] == 0) {
          List list = event["lists"];
          if (list != null) {
            state.recommendCommodityList = list;
            update();
          }
        }
      });
    });
  }

  // 获取广告内容
  void getAdvertising() {
    print('获取广告列表222');
    var params = {
      'adv_category': '1',
      'page_num': 1,
      'page_size': 10,
      'status_num_id': 3
    };
    Api.getAdvertising(params).listen((event) {
      if (event["code"] == 0 && event["list"] != null) {
        state.advertising = event['list'];
      } else {
        state.advertising = [];
      }
      update();
    });
  }

  /// 加入购物车
  void requestAddGoods(String ecShopNumId, String itemNumId, String styleNumId,
      String ecStyleNumId) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": 1.0,
      "ec_shop_num_id": ecShopNumId,
      "item_num_id": itemNumId,
      "style_num_id": styleNumId,
      "ec_style_num_id": ecStyleNumId,
      'access_token': SpUtil.getString('token'),
    };
    Api.addShoppingCart(params).listen((event) {
      print(event);
      if (event['code'] == 0) {
        mainLogic.getCartNum();
        toast('添加成功');
      } else {
        toast(event['message']);
      }
    });
  }

  void getAndGoThirdShop(int shopId) {
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "access_token": SpUtil.getString("token"),
      "ec_shop_num_id": shopId.toString(),
    };
    SpUtil.putInt('thirdStoreShopNum', shopId);
    Api.getShopInfo(params).listen((event) {
      if (event != null && event['code'] == 0) {
        if (event['ec_shop_infos'].length > 0) {
          SpUtil.remove(Config.GET_SHOP_INFO);
          var shoplistes = event['ec_shop_infos'];
          SpUtil.putObject(Config.GET_SHOP_INFO, {
            'shop_name': shoplistes[0]['ec_shop_name'],
            'shop_id': shoplistes[0]['ec_shop_num_id'],
            'super_ec_shop_num_id': shoplistes[0]['super_ec_shop_num_id'],
            'is_get_home': shoplistes[0]['is_get_home'],
            'is_express': shoplistes[0]['is_express'],
            'service_telphone': shoplistes[0]['service_telphone'],
            'is_pick_up': shoplistes[0]['is_pick_up'],
            'adr': shoplistes[0]['adr'],
            'telphone': shoplistes[0]['telphone'],
            'pickAdrId': shoplistes[0]['sub_unit_num_id'],
            'offShopName': shoplistes[0]['sub_unit_name'],
            'offShopadr': shoplistes[0]['sub_unit_adr'],
            'sub_unit_num_id': shoplistes[0]['sub_unit_num_id'],
            'isSupporySacn': true,
            'free_start_time': '1970-01-01' + shoplistes[0]['free_start_time'],
            'is_express_shops':
                shoplistes[0]['cloud_ec_shop_num_id'] == 1 ? true : false,
            'prv_num_id': shoplistes[0]['prv_num_id'],
            'prv_name': shoplistes[0]['prv_name'],
            'city_num_id': shoplistes[0]['city_num_id'],
            'city_name': shoplistes[0]['city_name'],
            'city_area_num_id': shoplistes[0]['city_area_num_id'],
            'city_area_name': shoplistes[0]['city_area_name'],
            'ec_shop_logo': shoplistes[0]['ec_shop_logo']
          });
          SpUtil.putInt(Config.IS_CHANGE_SHOP,
              SpUtil.getInt('storeShopNum') == shopId ? 0 : 1);
          Get.offAllNamed(RouteConfig.main, arguments: {'isChangeShop': true});
        }
      } else {
        toast(event['massage']);
      }
    });
  }
}
